package org.jeecg.modules.lab.exam.exam.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.modules.lab.cert.client.UserClient;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.exam.entity.LabExam;
import org.jeecg.modules.lab.exam.entity.LabExamDepart;
import org.jeecg.modules.lab.exam.entity.LabExamRepo;
import org.jeecg.modules.lab.exam.exam.service.ILabExamDepartService;
import org.jeecg.modules.lab.exam.exam.service.ILabExamRepoService;
import org.jeecg.modules.lab.exam.exam.service.ILabExamService;
import org.jeecg.modules.lab.exam.exam.vo.LabExamPage;
import org.jeecg.modules.lab.notify.entity.LabNotify;
import org.jeecg.modules.lab.notify.service.ILabNotifyService;
import org.jeecg.modules.lab.user.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 考试信息主表
 * @Author: jeecg-boot
 * @Date:   2023-08-26
 * @Version: V1.0
 */
@Api(tags="考试信息主表")
@RestController
@RequestMapping("/exam/labExam")
@Slf4j
public class LabExamController {
	@Autowired
	private ILabExamService labExamService;
	@Autowired
	private ILabExamDepartService labExamDepartService;
	@Autowired
	private ILabExamRepoService labExamRepoService;

	@Autowired
	private UserClient userClient;
	@Autowired
	private ILabNotifyService labNotifyService;

	@Autowired
	private ILabCronJobService labCronJobService;
	
	/**
	 * 分页列表查询
	 *
	 * @param labExam
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "考试信息主表-分页列表查询")
	@ApiOperation(value="考试信息主表-分页列表查询", notes="考试信息主表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<LabExam>> queryPageList(LabExam labExam,
												@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												@RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
												HttpServletRequest req) {
		QueryWrapper<LabExam> queryWrapper = QueryGenerator.initQueryWrapper(labExam, req.getParameterMap());
		Page<LabExam> page = new Page<LabExam>(pageNo, pageSize);
		IPage<LabExam> pageList = labExamService.page(page, queryWrapper);
		return Result.OK(pageList);
	}



	 /**
	  * 通过当前人员useID查询考试列表
	  *
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="考试信息主表-通过当前人员useID查询考试列表", notes="考试信息主表-通过当前人员useID查询考试列表")
	 @GetMapping(value = "/userExamList")
	 public Result<IPage<LabExamPage>> userExamList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												 @RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
												 HttpServletRequest req) {
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<LabExamPage> labExamPages = labExamService.selectExamListByUserId(loginUser.getId());
		 List<LabExamPage> PageList = labExamPages.stream().skip((pageNo - 1) * pageSize)
				 .limit(pageSize)
				 .collect(Collectors.toList());
		 Page<LabExamPage> page = new Page<LabExamPage>(pageNo, pageSize);
		 page.setTotal(labExamPages.size());
		 page.setRecords(PageList);
		 return Result.OK(page);
	 }

	
	/**
	 *   添加
	 *
	 * @param labExamPage
	 * @return
	 */
	@AutoLog(value = "考试信息主表-添加")
	@ApiOperation(value="考试信息主表-添加", notes="考试信息主表-添加")
//    @RequiresPermissions("exam:lab_exam:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody LabExamPage labExamPage) {
		LabExam labExam = new LabExam();
		BeanUtils.copyProperties(labExamPage, labExam);
		labExamService.saveMain(labExam, labExamPage.getLabExamDepartList(),labExamPage.getLabExamRepoList());

		if (MyEnum.sync) {
			long time = new Date().getTime();
			List<LabCronJob> jobs = new ArrayList<>();
			jobs.add(new LabCronJob("lab_exam", "0", time, 1));
			jobs.add(new LabCronJob("lab_exam_depart", "0", time, 2));
			jobs.add(new LabCronJob("lab_exam_repo", "0", time, 3));
			labCronJobService.saveBatch(jobs);
		}
		return Result.OK("添加成功！");
	}


	
	/**
	 *  编辑
	 *
	 * @param labExamPage
	 * @return
	 */
	@AutoLog(value = "考试信息主表-编辑")
	@ApiOperation(value="考试信息主表-编辑", notes="考试信息主表-编辑")
//    @RequiresPermissions("exam:lab_exam:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody LabExamPage labExamPage) {
		LabExam labExam = new LabExam();
		BeanUtils.copyProperties(labExamPage, labExam);
		LabExam labExamEntity = labExamService.getById(labExam.getId());
		if(labExamEntity==null) {
			return Result.error("未找到对应数据");
		}
		labExamService.updateMain(labExam, labExamPage.getLabExamDepartList(),labExamPage.getLabExamRepoList());

		if (MyEnum.sync) {
			long time = new Date().getTime();
			List<LabCronJob> jobs = new ArrayList<>();
			String condition1="exam_id='"+labExam.getId()+"'";
			String condition2="exam_id='"+labExam.getId()+"'";
			jobs.add(new LabCronJob("lab_exam", "1", time, 1));
			jobs.add(new LabCronJob("lab_exam_depart", "2",condition1, time, 2));
			jobs.add(new LabCronJob("lab_exam_repo", "2",condition2, time, 3));
			jobs.add(new LabCronJob("lab_exam_depart", "0", time, 4));
			jobs.add(new LabCronJob("lab_exam_repo", "0", time, 5));
			labCronJobService.saveBatch(jobs);
		}

		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "考试信息主表-通过id删除")
	@ApiOperation(value="考试信息主表-通过id删除", notes="考试信息主表-通过id删除")
//    @RequiresPermissions("exam:lab_exam:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		labExamService.delMain(id);

		if (MyEnum.sync) {
			long time = new Date().getTime();
			List<LabCronJob> jobs = new ArrayList<>();
			String condition1="id='"+id+"'";
			String condition2="exam_id='"+id+"'";
			jobs.add(new LabCronJob("lab_exam", "2",condition1, time, 1));
			jobs.add(new LabCronJob("lab_exam_depart", "2",condition2, time, 2));
			jobs.add(new LabCronJob("lab_exam_repo", "2",condition2, time, 3));
			labCronJobService.saveBatch(jobs);
		}
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "考试信息主表-批量删除")
	@ApiOperation(value="考试信息主表-批量删除", notes="考试信息主表-批量删除")
//    @RequiresPermissions("exam:lab_exam:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.labExamService.delBatchMain(Arrays.asList(ids.split(",")));

		if (MyEnum.sync) {
			long time = new Date().getTime();
			String[] idList = ids.split(",");
			List<LabCronJob> jobs = new ArrayList<>();
			for (int i = 0; i < idList.length; i++) {
				String condition1="exam_id='"+idList[i]+"'";
				String condition2="id='"+idList[i]+"'";
				jobs.add(new LabCronJob("lab_exam_depart","2",condition1,time));
				jobs.add(new LabCronJob("lab_exam_repo","2",condition1,time));
				jobs.add(new LabCronJob("lab_exam","2",condition2,time));
			}
			for (int i = 0; i < jobs.size(); i++) {
				jobs.get(i).setOrderNum(i+1);
			}
			labCronJobService.saveBatch(jobs);
		}
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "考试信息主表-通过id查询")
	@ApiOperation(value="考试信息主表-通过id查询", notes="考试信息主表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<LabExam> queryById(@RequestParam(name="id",required=true) String id) {
		LabExam labExam = labExamService.getById(id);
		if(labExam==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(labExam);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "考试人员/部门表-通过主表ID查询")
	@ApiOperation(value="考试人员/部门表-通过主表ID查询", notes="考试人员/部门表-通过主表ID查询")
	@GetMapping(value = "/queryLabExamDepartByMainId")
	public Result<IPage<LabExamDepart>> queryLabExamDepartListByMainId(@RequestParam(name="id",required=true) String id) {
		List<LabExamDepart> labExamDepartList = labExamDepartService.selectByMainId(id);
		IPage <LabExamDepart> page = new Page<>();
		page.setRecords(labExamDepartList);
		page.setTotal(labExamDepartList.size());
		return Result.OK(page);
	}

	 /**
	  * 查询题库中试题信息
	  *
	  * @return
	  */
	 @ApiOperation(value="考试信息主表-查询题库中试题信息", notes="考试信息主表-查询题库中试题信息")
	 @GetMapping(value = "/queryLabBankQuestion")
	 public Result<List<LabExamRepo>> queryLabBankQuestion() {
		 List<LabExamRepo> labExamRepoList = labExamRepoService.selectBankQuestion();
		 return Result.OK(labExamRepoList);
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "考试题库-通过主表ID查询")
	@ApiOperation(value="考试题库-通过主表ID查询", notes="考试题库-通过主表ID查询")
	@GetMapping(value = "/queryLabExamRepoByMainId")
	public Result<IPage<LabExamRepo>> queryLabExamRepoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<LabExamRepo> labExamRepoList = labExamRepoService.selectByMainId(id);
		IPage <LabExamRepo> page = new Page<>();
		page.setRecords(labExamRepoList);
		page.setTotal(labExamRepoList.size());
		return Result.OK(page);
	}

	 /**
	  *   考试发布
	  *
	  * @param id
	  * @param status
	  * @return
	  */
	 @AutoLog(value = "考试信息主表-考试发布")
	 @ApiOperation(value="考试信息主表-考试发布", notes="考试信息主表-考试发布")
	 @DeleteMapping(value = "/updateExam")
	 public Result<String> updateExam(@RequestParam(name="id",required=true) String id,
								   @RequestParam(name="status",required=true) String status) {
		 LabExam labExam = labExamService.getById(id);
		 labExam.setSynFlag("1");
		 if(labExam==null) {
			 return Result.error("未找到对应数据");
		 }
		 //todo：考试的消息通知；考试的业务id是什么？
		 if(status.equals("开放中")){
			 labExam.setStatus("开放中");
			 if("完全公开".equals(labExam.getOpenType()) || labExam.getExamDepart()==""){
				 labExam.setExamPerson(labExamDepartService.countByExamId().toString());
				 List<LabExamDepart> departList = labExamDepartService.list();//参与考试的所有部门
				departList.forEach(e-> {
					 //根据部门id查人员id
					 List<SysUser> users = userClient.queryUserByDepId(e.getDepartId(), null).getResult();
					 //根据人员id发布消息
					List<LabNotify> notifies = new ArrayList<>();
					for (int i = 0; i < users.size(); i++) {
						 LabNotify labNotify = new LabNotify();
						 labNotify.setNotName(labExam.getName());
						 labNotify.setNotTitlle("考核");
						 labNotify.setTaskId(labExam.getId());
						 labNotify.setTaskName("["+labExam.getOpenType()+"]的"+labExam.getName()+"考试");
						 labNotify.setEntrustId(labExam.getId());
						 labNotify.setUserId(users.get(i).getId());
						 labNotify.setNotStatus("未读");
						 labNotify.setPubTime(new Date());
						 notifies.add(labNotify);
					 }
					labNotifyService.saveBatch(notifies);
				 });
			 }else {
				 labExam.setExamPerson(labExamDepartService.countByExamId(id).toString());
				 LabExamDepart examDepart = labExamDepartService.getOne(new LambdaQueryWrapper<LabExamDepart>().eq(LabExamDepart::getDepartId, id));
				 List<SysUser> users = userClient.queryUserByDepId(examDepart.getDepartId(), null).getResult();
				 List<LabNotify> notifies = new ArrayList<>();
				 users.forEach(e->{
					 LabNotify labNotify = new LabNotify();
					 labNotify.setNotName(labExam.getName());
					 labNotify.setNotTitlle("考核");
					 labNotify.setTaskId(labExam.getId());
					 labNotify.setTaskName("["+labExam.getOpenType()+"]的"+labExam.getName()+"考试");
					 labNotify.setEntrustId(labExam.getId());
					 labNotify.setUserId(e.getId());
					 labNotify.setNotStatus("未读");
					 labNotify.setPubTime(new Date());
					 notifies.add(labNotify);
				 });
				 labNotifyService.saveBatch(notifies);
			 }
			 labExamService.saveOrUpdate(labExam);

			 if (MyEnum.sync) {
				 long time = new Date().getTime();
				 List<LabCronJob> jobs = new ArrayList<>();
				 jobs.add(new LabCronJob("lab_notify", "0", time, 1));
				 jobs.add(new LabCronJob("lab_exam", "1", time, 2));
				 labCronJobService.saveBatch(jobs);
			 }
			 return Result.OK("开放成功!");
		 }else {
			 labExam.setStatus("已结束");
			 labExamService.saveOrUpdate(labExam);

			 if (MyEnum.sync) {
				 long time = new Date().getTime();
				 LabCronJob job=new LabCronJob("lab_exam", "1", time, 1);
				 labCronJobService.save(job);
			 }
			 return Result.OK("结束成功!");
		 }
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param labExam
    */
//    @RequiresPermissions("exam:lab_exam:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabExam labExam) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<LabExam> queryWrapper = QueryGenerator.initQueryWrapper(labExam, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<LabExam>  labExamList = labExamService.list(queryWrapper);

      // Step.3 组装pageList
      List<LabExamPage> pageList = new ArrayList<LabExamPage>();
      for (LabExam main : labExamList) {
          LabExamPage vo = new LabExamPage();
          BeanUtils.copyProperties(main, vo);
          List<LabExamDepart> labExamDepartList = labExamDepartService.selectByMainId(main.getId());
          vo.setLabExamDepartList(labExamDepartList);
          List<LabExamRepo> labExamRepoList = labExamRepoService.selectByMainId(main.getId());
          vo.setLabExamRepoList(labExamRepoList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "考试信息主表列表");
      mv.addObject(NormalExcelConstants.CLASS, LabExamPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("考试信息主表数据", "导出人:"+sysUser.getRealname(), "考试信息主表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
//    @RequiresPermissions("exam:lab_exam:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<LabExamPage> list = ExcelImportUtil.importExcel(file.getInputStream(), LabExamPage.class, params);
              for (LabExamPage page : list) {
                  LabExam po = new LabExam();
                  BeanUtils.copyProperties(page, po);
                  labExamService.saveMain(po, page.getLabExamDepartList(),page.getLabExamRepoList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
